package Principal;

import static Principal.VentanaPrincipal.logger;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import preparedstatement.DebugLevel;
import preparedstatement.StatementFactory;
/**
 *
 * @author Pascual Guerrero
 */
public class Usuario extends javax.swing.JFrame {

    Connection con = null;
    PreparedStatement ps;
    ResultSet rs;
    int idsucursal;
    static boolean otro = false;
    static VentanaPrincipal pov;
    public static int niv;
    InetAddress ip;
    StringBuilder sb;
    String nombreSucursal;
    int queSucursal = 1;
    int ncaja;
    Properties propiedades;
    jcProperties editarPropiedades;

    public Usuario() {
        initComponents();
        setLocationRelativeTo(null);
        cargarPropiedades();
        //this.setAlwaysOnTop(true);
        //this.requestFocus();
        new Bloquear(this).block();
        new cache_connection();
        new local_connection();
        //new cache_connection();
        pov = new VentanaPrincipal();

        ImageIcon icon = new ImageIcon(Usuario.class.getResource("/Imagenes/TeslaBEM_acceso.jpg"));
        Image img = icon.getImage();
        BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        Graphics g = bi.createGraphics();
        g.drawImage(img, 0, 0, 300, 100, null);
        icon = new ImageIcon(bi);
        jLabel3.setIcon(icon);
        getRootPane().setDefaultButton(jButton1);
        con = local_connection.cn;

        extraermac();

    }

    private void cargarPropiedades() {
        editarPropiedades = new jcProperties();
        propiedades = new Properties();
        try {
            propiedades = editarPropiedades.getProperties();
            ncaja = Integer.valueOf(propiedades.getProperty("caja"));
            queSucursal = Integer.valueOf(propiedades.getProperty("sucursal"));
        } catch (NumberFormatException e) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, e);

        }

    }
    private void guardarPropiedades(){
        try {
            FileOutputStream os = null;
            propiedades = editarPropiedades.getProperties();
                    propiedades.setProperty("sucursal", String.valueOf(queSucursal));
                     propiedades.setProperty("caja", String.valueOf(ncaja));
            os=new FileOutputStream("Propiedades.properties");
            propiedades.store(os, "Base de Datos Local");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Usuario.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Usuario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jPasswordField1 = new javax.swing.JPasswordField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Acceso a TeslaBEM POV (Beta)");
        setIconImage(new ImageIcon(getClass().getResource("/Imagenes/logo_rayito.png")).getImage());
        setResizable(false);

        jLabel1.setText("Codigo de Acceso:");

        jButton1.setText("Acceder");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText("Acceso:");

        jLabel3.setText("jLabel3");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton1)))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(0, 0, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jButton1)
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addContainerGap(89, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        Double caja = null;
        int sesionId = -1;
        if (!String.valueOf(jPasswordField1.getPassword()).equals("")) {
            try {
                if (validar()) //Comentar o Descomentar
                {
                    int id, categoria;
                    String pass = String.valueOf(jPasswordField1.getPassword());
                    ps = (PreparedStatement) con.prepareStatement("SELECT id_persona, nombre, categoria FROM personas WHERE pass = '" + pass + "' and tipo='Empleado'");
                    rs = ps.executeQuery();
                    if (rs.next()) {
                        categoria = rs.getInt(3);
                        id = rs.getInt(1);
                        JOptionPane.showMessageDialog(this, "Bienvenido " + rs.getString(2));
                        VentanaPrincipal.nusuario=rs.getString(2);
                        // Dejo el  usuario su sesion abierta?

                        ps = (PreparedStatement) con.prepareStatement("SELECT inicio,caja,sucursal,nombre,sesion.id FROM sesion join sucursales on sesion.sucursal = sucursales.id WHERE idusuario = ? AND fin is null LIMIT 1");
                        ps.setInt(1, id);
                        rs = ps.executeQuery();
                        if (rs.next()) {
                            queSucursal=rs.getInt("sucursal");
                            ncaja=rs.getInt("caja");
                            String date = rs.getString(1);
                            nombreSucursal = rs.getString(4);
                            sesionId = rs.getInt("id");
                            JOptionPane.showMessageDialog(this, "Reestableciendo sesion...\nIniciadia en: " + date);
                            guardarPropiedades();
                        } else {
                            while (caja == null) {
                                try {
                                    caja = new Double(JOptionPane.showInputDialog("Por favor ingresa el dinero en caja"));
                                    ps=local_connection.cn.prepareStatement("select nombre from sucursales where id=?");
                                    ps.setInt(1,queSucursal);
                                    rs=ps.executeQuery();
                                    rs.next();
                                    nombreSucursal=rs.getString(1);
                                } catch (HeadlessException | NumberFormatException nfe) {
                                   // VentanaPrincipal.logger.log(Level.SEVERE, null, nfe);
                                }
                            }

                            // Guardamos la informacion del usuario en la tabla sesion
                            ps = StatementFactory.getStatement(local_connection.cn, "INSERT INTO sesion(idusuario,inicio,iniciocaja,caja,sucursal) VALUES(?,CURRENT_TIMESTAMP,?,?,?)", DebugLevel.ON);
                            ps.setInt(1, id);
                            ps.setDouble(2, caja);
                            ps.setInt(3, ncaja);
                            ps.setInt(4, queSucursal);
                            ps.execute();
                            VentanaPrincipal.guardarCache(ps, "Sesion", false);
                            // Obtenemos el id de la sesion

                            ps = (PreparedStatement) con.prepareStatement("select last_insert_id()");
                            rs = ps.executeQuery();
                            rs.next();
                            sesionId = rs.getInt(1);
                        }
                        pov.setUsuario(id, categoria, sesionId, ncaja, queSucursal, nombreSucursal);
                        PanelVentas panel = new PanelVentas();
                       // BizLafControl.get().setStyle(panel, BizLafStyles.HEADER);
                        pov.jTabbedPane1.add("Venta " + (pov.jTabbedPane1.getTabCount() + 1), panel);
                        pov.setVisible(true);
                        Thread dato = new Thread(new actualizarThread());
                        dato.start();
                        this.dispose();
                    } else {
                        JOptionPane.showMessageDialog(this, "Password incorrecto, intentelo de nuevo");
                        jPasswordField1.setText("");
                        jPasswordField1.requestFocus();
                    }
                }
            }//Descomentar para correr metodo
            //Si el usuario ya esta activo, ahora se pide la contraseña de la sucursal
            //Una vez que la digite bien, se realiza un Update a la tabla para relacionar
            //el campo id de la tabla Sucursales con sucursal de la tabla Activo 
            catch (SQLException ex) {
                VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
            }
        }


    }//GEN-LAST:event_jButton1ActionPerformed

    public void setOtro(boolean n) {
        otro = n;
    }

    public void extraermac() {

        //En esta parte se obtiene la Mac Address de la computadora    
        try {

            ip = InetAddress.getLocalHost();
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            byte[] mac = network.getHardwareAddress();

            sb = new StringBuilder();
            for (int i = 0; i < mac.length; i++) {
                sb.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? "-" : ""));
            }
            //Checho si la mac address se encuentra en la base de datos
            try {
                ps = (PreparedStatement) con.prepareStatement("SELECT * from activo where macaddress='" + sb.toString() + "'");
                rs = ps.executeQuery();
                if (!rs.next()) {
                    ps = (PreparedStatement) con.prepareStatement("SELECT nombre from activo join sucursales on activo.sucursal = sucursales.id where macaddress = '" + sb.toString() + "'");
                    rs = ps.executeQuery();
                    //Si no existe entonces la guardo en la tabla de activo, ademas de sacar el id que se le asigno
                    if (!rs.next()) {
                        ps = StatementFactory.getStatement(local_connection.cn, "INSERT INTO activo(macaddress) VALUES(?)", DebugLevel.ON);
                        ps.setString(1, sb.toString());
                        ps.execute();
                        ps = (PreparedStatement) con.prepareStatement("select last_insert_id()");
                        rs = ps.executeQuery();
                        rs.next();
                        idsucursal = rs.getInt(1);
                    } else {
                        nombreSucursal = rs.getString(1);
                    }
                }
            } catch (SQLException ex1) {
                VentanaPrincipal.logger.log(Level.SEVERE, null, ex1);
            }
        } catch (UnknownHostException | SocketException e) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, e);
        }
    }

    public boolean validar() throws SQLException {
        try {
            //Verifico si la macaddress se encuentra en la BD y si se encuentra activo (0==No activo y 0!=Esta activo)
            ps = (PreparedStatement) con.prepareStatement("SELECT estado from activo where macaddress = '" + sb.toString() + "'");
            rs = ps.executeQuery();
            if (!rs.next() || (rs.getInt(1) == 0)) {
                this.setVisible(false);
                JOptionPane.showMessageDialog(null, "Envia un correo a soporte@teslabem.com con el siguiente numero\nID= " + idsucursal);
                System.exit(0);
            } else {
                return true;
            }
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
        return false;
    }

    /**
     * Main principal donde
     *
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
           /* for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                    
                }
            }*/
            UIManager.setLookAndFeel("de.centigrade.bizlaf.BizLookAndFeel");
        } catch (InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Usuario.class.getName()).log(Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Usuario().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPasswordField jPasswordField1;
    // End of variables declaration//GEN-END:variables
    cambiarConexion miconexion;
}
